#!/bin/bash

HERE=$(dirname $(readlink -f "${0}"))
BRANCH=${GALACTEEK_BRANCH:-pimp-my-dweb}

export GALACTEEK_COMMIT_SHA="@@COMMIT_SHA@@"

# conda's xkbcommon package hardcodes XKB_CONFIG_ROOT it seems :|
# Set XKB_CONFIG_ROOT for when we run inside wayland
# https://gitlab.com/galacteek/galacteek/-/issues/3
export XKB_CONFIG_ROOT=/usr/share/X11/xkb

# Custom magic.mgc db
export GALACTEEK_MAGIC_DBPATH=${HERE}/usr/share/file/magic-galacteek.mgc

# Use certifi's cacert.pem for SSL_CERT_FILE
export SSL_CERT_FILE=${HERE}/usr/lib/python3.7/site-packages/certifi/cacert.pem

export FONTCONFIG_FILE=$HERE/usr/etc/fonts/fonts.conf
export FONTCONFIG_PATH=$HERE/usr/etc/fonts/

export PATH=${HERE}/usr/bin:$PATH
export LD_LIBRARY_PATH=${HERE}/usr/lib:$LD_LIBRARY_PATH

export PYTHONHOME=${HERE}/usr
export PYTHONPATH=${HERE}/usr/lib/python3.7/site-packages:${PYTHONPATH}

# Configure using galacteek-starter
eval export $("${HERE}"/usr/bin/python "${HERE}"/usr/bin/galacteek-starter --venv-info)

export PYTHONPATH=${GVENV_SITE_PACKAGES}:${PYTHONPATH}

export QT_QPA_PLATFORM_PLUGIN_PATH=${HERE}/usr/lib/python3.7/site-packages/PyQt5/Qt5/plugins/platforms
export QT_STYLE_OVERRIDE=Fusion

APPIQT_LIBPATH=${HERE}/usr/lib/python3.7/site-packages/PyQt5/Qt5/lib

if [ ! -z "${container}" ] && [ x"${container}" == x"firejail" ]; then
	# Disable qtwebengine sandboxing if running inside firejail
	export QTWEBENGINE_DISABLE_SANDBOX=1
fi

if [ ! -z ${APPIMAGE_LIBCHECK} ]; then
	_LIBS="$QT_QPA_PLATFORM_PLUGIN_PATH/libqxcb.so \
		$APPIQT_LIBPATH/libQt5*"

	for lib in $_LIBS; do
		echo "ldd check: $lib"
		ldd $lib|grep -i 'not found'
	done
	exit 1
fi

BINARY_PATH=$APPIMAGE
BINARY_NAME=$(basename "$APPIMAGE")

"${HERE}"/usr/bin/python "${HERE}"/usr/bin/galacteek-starter \
	--from-appimage \
	--binary-name="${BINARY_NAME}" --binary-path="${BINARY_PATH}" \
	--no-release-check "$@"
